package org.yi.web.friendlink;

import org.apache.commons.lang.StringUtils;
import org.yi.core.annotation.Action;
import org.yi.core.enums.CommonStateEnum;
import org.yi.core.model.Pagination;
import org.yi.web.base.BaseController;
import org.yi.web.friendlink.entity.FriendLinkEntity;

import com.jfinal.plugin.activerecord.Page;

@Action(action="/admin/friendlink")
public class FriendLinkController extends BaseController {
	
	public void index() {
		Pagination pager = getPager();
		Page<FriendLinkEntity> page = FriendLinkEntity.dao.getPager(pager);
		setAttr("page", page);
		render("list.html");
	}
	
	public void add() {
		render("add.html");
	}
	
	public void save() {
		FriendLinkEntity link = getModel(FriendLinkEntity.class);
		try {
			if(FriendLinkEntity.dao.getByKeyword(link.getStr("keyword")) != null) {
				addError("关键词 [" + link.getStr("keywords") + "] 已存在!");
				keepPara();
				render("add.html");
			} else if(FriendLinkEntity.dao.getByUrl(link.getStr("url")) != null) {
				addError("链接已存在!");
				keepPara();
				render("add.html");
			} else {
				link.save();
				redirect("/admin/friendlink");
			}
		} catch(Exception e) {
			addError("save [" + link.getStr("keywords") + "] error, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void edit() {
		String id = getPara("id");
		if(StringUtils.isNotBlank(id)) {
			FriendLinkEntity entity = FriendLinkEntity.dao.findById(id);
			setAttr("f", entity);
			render("add.html");
		} else {
			redirect("/admin/friendlink");
		}
	}
	
	public void doEdit() {
		FriendLinkEntity link = getModel(FriendLinkEntity.class);
		try {
			link.update();
			redirect("/admin/friendlink");
		} catch(Exception e) {
			addError("update [" + link.getStr("keywords") + "] error, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void lock() {
		FriendLinkEntity entity = FriendLinkEntity.dao.findById(getPara("id"));
		if(entity!=null) {
			if(entity.getInt("state") == CommonStateEnum.ENABLE.getCode()){
				entity.set("state", CommonStateEnum.DISABLE.getCode());
			} else {
				entity.set("state", CommonStateEnum.ENABLE.getCode());
			}
			entity.update();
			redirect("/admin/friendlink");
		}
	}
	
	public void delete() {
		FriendLinkEntity.dao.deleteById(getPara("id"));
		redirect("/admin/friendlink");
	}
}
